package com.director.core;

import com.director.core.crud.CRUDResult;

/**
 * @author Simone Ricciardi
 * @version 1.0, 02/27/2012
 */
public class DirectCRUDAction extends DirectAction {

   enum API {
      create, read, update, destroy;

      static boolean isACRUDMethod(String methodName) {
         API[] apis = API.values();
         for(API api : apis) {
            if(api.name().equals(methodName)) {
               return true;
            }
         }
         return false;
      }
   }

   public DirectCRUDAction(String namespace, String actionName, Class actionClass) {
      super(namespace, actionName, actionClass);
   }

   @Override
   DirectTransactionResult invokeMethod(String methodName, DirectTransactionData data) throws DirectException {
      if(API.isACRUDMethod(methodName)) {
         return this.handleCRUDInvocation(methodName, data);
      } else {
         return super.invokeMethod(methodName, data);
      }
   }

   private DirectTransactionResult handleCRUDInvocation(String methodName, DirectTransactionData data) {
      DirectTransactionResult result = null;
      boolean success = true;
      String message = null;
      try {
         result = super.invokeMethod(methodName, data);
      } catch(DirectException e) {
         success = false;
         message = e.getMessage();
      }
      return new CRUDResult(success, message, result);
   }
}
